import json
import logging
import traceback
from datetime import datetime
from django.db import transaction
from django.http import JsonResponse
from rest_framework import status
from Model.models import Address as A
from Model.modelsView import AddressInfo
from tools.Tools import check_text, getCurrentUser, createHandleLog

logger_info = logging.getLogger('info')
res = dict()


def Address(request):
    res.clear()
    try:
        if request.method == 'GET':
            return queryAddress(request)
        elif request.method == 'POST':
            return createAddress(request)
        elif request.method == 'PUT':
            return modifyAddress(request)
        elif request.method == 'DELETE':
            return delAddress(request)
    except Exception as e:
        print(e)
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 200
        res['message'] = '请求错误!'
        return JsonResponse(res, status=status.HTTP_400_BAD_REQUEST)


# 获取蓝牌地址信息
def queryAddress(request):
    current = request.GET.get('current')
    pageSize = request.GET.get('pageSize')
    name = request.GET.get('name')
    district_id = request.GET.get('district_id')
    subdistrict_id = request.GET.get('subdistrict_id')
    community_id = request.GET.get('community_id')
    address = AddressInfo.objects.all()
    if check_text(name):
        address = address.objectsfilter(name__contains=name)
    if check_text(district_id):
        address = address.filter(district_id=district_id)
    if check_text(subdistrict_id):
        address = address.filter(subdistrict_id=subdistrict_id)
    if check_text(community_id):
        address = address.filter(community_id=community_id)
    total = address.count()
    dataJson = list(
        address.values()[int(pageSize) * int(current) - int(pageSize):int(pageSize) * int(current)])
    res['status'] = 200
    res['data'] = dataJson
    res['total'] = total
    res['message'] = '请求成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 新建蓝牌地址
@transaction.atomic
def createAddress(request):
    body = json.loads(request.body)
    name = body.get('name')
    district_id = body.get('district_id')
    subdistrict_id = body.get('subdistrict_id')
    community_id = body.get('community_id')
    address = A.objects.create()
    address.address_id = address.id
    address.district_id = district_id
    address.subdistrict_id = subdistrict_id
    address.community_id = community_id
    address.create_time = datetime.now()
    address.name = name
    createHandleLog('新增蓝牌地址', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《新增蓝牌地址》权限 新增内容 {body}')
    address.save()
    res['status'] = 200
    res['message'] = '新建成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 修改蓝牌地址
@transaction.atomic
def modifyAddress(request):
    body = json.loads(request.body)
    address_id = body.get('address_id')
    name = body.get('name')
    district_id = body.get('district_id')
    subdistrict_id = body.get('subdistrict_id')
    community_id = body.get('community_id')
    address = A.objects.get(address_id=address_id)
    address.district_id = district_id
    address.subdistrict_id = subdistrict_id
    address.community_id = community_id
    address.name = name
    createHandleLog('修改蓝牌地址', str(getCurrentUser(request)), body)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《修改蓝牌地址》权限 新增内容 {body}')
    address.save()
    res['status'] = 200
    res['message'] = '修改成功'
    return JsonResponse(res, status=status.HTTP_200_OK)


# 删除蓝牌地址
@transaction.atomic
def delAddress(request):
    address_id = request.GET.get('address_id')
    address = A.objects.get(address_id=address_id)
    createHandleLog('删除蓝牌地址', str(getCurrentUser(request)), address.name)
    logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《删除蓝牌地址》权限 删除 {address.name}')
    address.delete()
    res['status'] = 200
    res['message'] = '删除成功'
    return JsonResponse(res, status=status.HTTP_200_OK)
